package com.xxy.partnermatch.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xxy.partnermatch.common.BaseResponse;
import com.xxy.partnermatch.common.DeleteRequest;
import com.xxy.partnermatch.model.enums.ErrorCode;
import com.xxy.partnermatch.exception.BusinessException;
import com.xxy.partnermatch.model.dto.UserLoginRequest;
import com.xxy.partnermatch.model.dto.UserRegisterRequest;
import com.xxy.partnermatch.model.entity.User;
import com.xxy.partnermatch.model.vo.UserVO;
import com.xxy.partnermatch.service.UserService;
import com.xxy.partnermatch.utils.ResultUtils;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * ClassName: UserController
 * Package: com.xxy.usercenter.controller
 * Description: 用户请求Controller
 *
 * @Author 十一
 * @Create 2024/11/14 15:58
 * @Version 1.0
 */
@Tag(name = "用户管理")     // 描述controller类的作用
@CrossOrigin(origins = {"http://localhost:3000"})   // 这里填写前端项目的访问路径
@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {

    @Resource
    private UserService userService;

    @Resource
    private RedisTemplate redisTemplate;

    /**
     * 用户注册
     *
     * @param userRegisterRequest 用户注册请求体
     * @return 新用户id
     */
    @Operation(summary = "用户注册")
    @PostMapping("/register")
    public BaseResponse<Long> userRegister(@RequestBody UserRegisterRequest userRegisterRequest) {
        if (userRegisterRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        long result = userService.userRegister(userRegisterRequest);
        return ResultUtils.success(result);
    }

    /**
     * 用户登录
     *
     * @param userLoginRequest 用户登录请求体
     * @param request          request请求对象
     * @return 当前登录用户
     */
    @Operation(summary = "用户登录")
    @PostMapping("/login")
    public BaseResponse<UserVO> userRegister(@RequestBody UserLoginRequest userLoginRequest, HttpServletRequest request) {
        if (userLoginRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        String userAccount = userLoginRequest.getUserAccount();
        String userPassword = userLoginRequest.getUserPassword();
        // 判断参数
        if (StringUtils.isAnyBlank(userAccount, userPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        UserVO userVO = userService.userLogin(userAccount, userPassword, request);
        return ResultUtils.success(userVO);
    }

    /**
     * 用户注销
     *
     * @param request request请求对象
     * @return 返回值大于0表示注销成功
     */
    @Operation(summary = "用户注销")
    @PostMapping("/logout")
    public BaseResponse<Integer> userLogout(HttpServletRequest request) {
        if (request == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        int result = userService.userLogout(request);
        return ResultUtils.success(result);
    }

    /**
     * 获取当前登录用户
     *
     * @param request request请求对象
     * @return 当前登录用户
     */
    @Operation(summary = "获取当前登录用户")
    @GetMapping("/current")
    public BaseResponse<UserVO> getCurrentUser(HttpServletRequest request) {
        if (request == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        UserVO userVO = userService.getCurrentUser(request);
        return ResultUtils.success(userVO);
    }

    /**
     * 根据id删除用户
     *
     * @param deleteRequest 用户删除请求体
     * @param request       request请求对象
     * @return 返回值大于0表示删除成功
     */
    @Operation(summary = "根据id删除用户")
    @DeleteMapping("/delete")
    public BaseResponse<Integer> deleteUser(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() < 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        int result = userService.deleteUser(deleteRequest.getId(), request);
        return ResultUtils.success(result);
    }

    /**
     * 根据用户名查找用户 (仅管理员可查询)
     *
     * @param username 用户名
     * @param request  request请求对象
     * @return 符合要求的用户集合
     */
    @Operation(summary = "根据用户名查找用户 (仅管理员可查询)")
    @GetMapping("/search")
    public BaseResponse<List<UserVO>> searchUsers(String username, HttpServletRequest request) {
        List<UserVO> resultList = userService.searchUsers(username, request);
        return ResultUtils.success(resultList);
    }

    /**
     * 根据标签搜索用户
     *
     * @param tagNameList 标签列表
     * @return 用户列表
     */
    @Operation(summary = "根据标签搜索用户")
    @GetMapping("/search/tags")
    public BaseResponse<List<UserVO>> searchUsersByTags(@RequestParam(required = false) List<String> tagNameList) {
        if (CollectionUtils.isEmpty(tagNameList)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        List<UserVO> userVOList = userService.searchUserVOByTags(tagNameList);
        return ResultUtils.success(userVOList);
    }

    /**
     * 更新用户信息
     *
     * @param user    需要更新的用户
     * @param request request请求对象
     * @return 是否更新成功
     */
    @Operation(summary = "更新用户信息")
    @PostMapping("/update")
    public BaseResponse<Integer> updateUser(@RequestBody User user, HttpServletRequest request) {
        // 1. 验证参数是否为空
        if (user == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // 2. 鉴权
        UserVO loginUser = userService.getLoginUser(request);
        // 3. 更新用户
        int result = userService.updateUser(user, loginUser);
        return ResultUtils.success(result);
    }

    /**
     * 推荐用户
     * todo 推荐多个，未实现
     *
     * @param pageSize 每页有多少条数据
     * @param pageNum  请求第几页
     * @param request  request请求对象
     * @return 用户列表
     */
    @Operation(summary = "推荐用户")
    @GetMapping("/recommend")
    public BaseResponse<Page<User>> recommendUsers(long pageSize, long pageNum, HttpServletRequest request) {
        UserVO loginUser = userService.getLoginUser(request);
        String redisKey = String.format("xuxuanya:user:recommend: %s", loginUser.getId());
        ValueOperations<String, Object> valueOperations = redisTemplate.opsForValue();
        // 1. 如果有缓存，直接读取缓存
        Page<User> userPage = (Page<User>) valueOperations.get(redisKey);
        if (userPage != null) {
            return ResultUtils.success(userPage);
        }
        // 2. 无缓存, 直接查询数据库
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        userPage = userService.page(new Page<>(pageNum, pageSize), queryWrapper);
        // 3. 写缓存
        try {
            // 并设置过期时间
            valueOperations.set(redisKey, userPage, 30000, TimeUnit.MILLISECONDS);
        } catch (Exception e) {
            log.error("redis set key error: ", e);
        }
        return ResultUtils.success(userPage);
    }

    /**
     * 获取匹配用户
     *
     * @param num     匹配用户数量
     * @param request request请求对象
     * @return 用户列表
     */
    @Operation(summary = "获取匹配用户")
    @GetMapping("/match")
    public BaseResponse<List<UserVO>> matchUsers(long num, HttpServletRequest request) {
        if (num <= 0 || num >= 20) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        UserVO loginUser = userService.getLoginUser(request);
        return ResultUtils.success(userService.matchUsers(num, loginUser));
    }

}
